<?php

namespace app\agent\controller;

use app\models\{AgentArea, Agent as Agents, Region, Order, Riderlist, RiderStreet, OrderProduct, Graborder, Coupon, User as Users};
use think\Db;
use think\Validate;

class Orders extends Base
{


    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new Order();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['id|ordersn|name|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['created'])) {
                $start = $post['created']['startime'] ?? date('Y-m-d H:i:s');
                $end = $post['created']['endtime'] ?? date('Y-m-d H:i:s');
                $where[] = ['created', 'between', [$start, $end]];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['payment'])) {
                $where[] = ['payment', '=', $post['payment']];
            }
            if (!empty($post['riderid'])) {
                $where[] = ['orderid', '=', $post['riderid']];
            }
            if (!empty($post['street'])) {
                $where[] = ['street', '=', $post['street']];
            } elseif (!empty($post['area'])) {
                $where[] = ['area', '=', $post['area']];
            } elseif (!empty($post['city'])) {
                $where[] = ['city', '=', $post['city']];
            } elseif (!empty($post['province'])) {
                $where[] = ['province', '=', $post['province']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $street = getdrees($lists['street'], 2);
                $lists['province_text'] = $street['province'];
                $lists['city_text'] = $street['city'];
                $lists['area_text'] = $street['area'];
                $lists['street_text'] = $street['street'];
                $lists['appointment'] = !empty($lists['appointment']) ? $lists['appointment'] : '无';
                $lists['status_text'] = $lists->status_text;
                $lists['payment_text'] = $lists->payment_text;
                $lists['ridername'] = '无';
                $lists['ridermobile'] = '无';
                if ($lists['orderid'] > 0) {
                    $rider = (new Riderlist())->where('id', $lists['orderid'])->field('name,mobile')->find();
                    $lists['ridername'] = $rider['name'] ?? '无';
                    $lists['ridermobile'] = $rider['mobile'] ?? '无';
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id']])->column('riderid');
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select(),
                'rider' => (new Riderlist())->where(['id' => $riderid])
                    ->field('id,name,mobile,cards')
                    ->select()
            ]);
        }
    }

    public function order_edit()
    {
        $id = $this->request->get('id/d', 0);
        $row = (new Order())->where('id', $id)->find();
        if ($row) {
            $row['agent_name'] = (new Agents())->where('id', $row['agentid'])->field('nickname,accounts')->find();
            $row['product'] = (new OrderProduct())->where('ordersn', $row['ordersn'])->select();
            $row['coupons'] = json_decode($row['coupons'], true);
            $row['rzmoney'] = (new Coupon())->where(['id' => $row['coupons'], 'agentid' => $row['agentid'], 'types' => 2])->sum('btmoney'); //优惠券金额
            $street = getdrees($row['street'], 2);
            $row['province_text'] = $street['province'];
            $row['city_text'] = $street['city'];
            $row['area_text'] = $street['area'];
            $row['street_text'] = $street['street'];
            $row['appointment'] = !empty($row['appointment']) ? $row['appointment'] : '无';
            $row['status_text'] = $row->status_text;
            $row['payment_text'] = $row->payment_text;
            $row['ridername'] = '无';
            $row['ridermobile'] = '无';
            if ($row['orderid'] > 0) {
                $rider = (new Riderlist())->where('id', $row['orderid'])->field('name,mobile')->find();
                $row['ridername'] = $rider['name'] ?? '无';
                $row['ridermobile'] = $rider['mobile'] ?? '无';
            }
            $row['images1'] = json_decode($row['images1'], true) ?? [];
            if (!is_array($row['images1'])) {
                $row['images1'] = [];
            }
            $row['images2'] = json_decode($row['images2'], true) ?? [];
            if (!is_array($row['images2'])) {
                $row['images2'] = [];
            }
        }
        return view('', [
            'row' => $row
        ]);
    }

    public function order_status()
    {
        if ($this->request->isAjax()) {
            $data = input();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require|in:2,3,4,5'
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
                'status.in' => '状态类型不正确',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $order = (new Order())->where(['id' => $data['id'], 'agentid' => $this->request->agent['id']])->find();
            if (empty($order)) {
                return json(['code' => 1, 'msg' =>  '订单不存在']);
            }
            switch ($data['status']) {
                case '2':
                    # code...
                    break;
                case '3':
                    if ($order['status'] != 2 && $order['status'] != 3) {
                        return json(['code' => 1, 'msg' =>  '订单未付款状态，无法执行该操作']);
                    }
                    if (empty($data['ridermobile'])) {
                        return json(['code' => 1, 'msg' =>  '未填写师傅账号']);
                    }
                    $rider = (new Riderlist())->where('mobile', $data['ridermobile'])->find();
                    if (empty($rider)) {
                        return json(['code' => 1, 'msg' =>  '师傅不存在,请确保账号正确']);
                    }
                    if ($rider['id'] == $order['orderid']) {
                        return json(['code' => 1, 'msg' =>  '该订单已属于该人员，无需更改']);
                    }
                    $data['orderid'] = $rider['id'];
                    $data['ordertime'] = date('Y-m-d H:i:s');
                    break;
                case '4':
                    if ($order['status'] != 2 && $order['status'] != 3) {
                        return json(['code' => 1, 'msg' =>  '订单状态无法执行该操作']);
                    }
                    $data['endtime'] = date('Y-m-d H:i:s');
                    $user = (new Users())->where('id', $order['user_id'])->find();
                    break;
                case '5':
                    if ($order['status'] != 2 && $order['status'] != 3 && $order['status'] != 1) {
                        return json(['code' => 1, 'msg' =>  '订单状态无法执行该操作']);
                    }
                    $data['caceltime'] = date('Y-m-d H:i:s');
                    if ($order['total'] > 0 && $order['payment'] > 1) {
                        $data['refund'] = 2;
                    }
                    break;
                default:
                    return json(['code' => 1, 'msg' =>  '订单类型错误']);
                    break;
            }
            $coupon = json_decode($order['coupons'], true) ?? [];
            Db::startTrans();
            try {
                (new Order())->allowfield(true)->save($data, ['id' => $data['id']]);
                if ($data['status'] == 3) {
                    (new Graborder())->insert(['user_id' => $data['id'], 'comeuser_id' => $order['orderid'], 'orderid' => $order['id'], 'type' => 3]);
                }
                if ($data['status'] == 4 && !empty($user)) {
                    (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 1, $order['id'], '下单赠送');
                }
                if ($order['coupon'] > 0 && $data['status'] == 5) {
                    (new Coupon())->where('id', $order['coupon'])->update(['status' => 1]);
                }
                if ($data['status'] == 5 && count($coupon) > 0) {
                    (new Coupon())->where(['id' => $coupon])->update(['status' => 1]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'msg' => '操作失败']);
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        }
    }
}
